package org.redmagic.client.utils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.google.common.collect.ImmutableList;

public class DocumentUtils {

	private static final Log LOG = LogFactory.getLog(DocumentUtils.class);
	
	public static List<String> parseAttempt(Element attempt) {
		
		List<String> results = new ArrayList<String>();
		
		if (attempt.hasChildNodes()) {
			
			// Parse tags and return them as a list
			NodeList tags = ((Element) attempt.getElementsByTagName("tags").item(0)).getElementsByTagName("*");
			for (int i = 0; i < tags.getLength(); i++) {
				results.add(createTag((Element) tags.item(i)));
			}
			return results;
			
		} else {
			
			// No tags, return an empty list
			return results;
		}
	}
	
	private static String createTag(Element tag) {
		
		String rval = null;
		
		try {
			
			String methodName = "create" + StringUtils.capitalize(tag.getNodeName());
			LOG.info("Looking for method: " + methodName);
			
			Method method = DocumentUtils.class.getMethod(methodName, Element.class);
			
			LOG.info("Creating tag with method: " + method.toString());
			
			rval = (String) method.invoke(null, tag);

		} catch (Exception e) {
			throw new RuntimeException("Unable to find method", e);
		}	
		
		return rval;
	}
	
	public static String createHostnameTag(Element tag) {
		
		return "hostname";
	}
	
	public static String createSingleTag(Element tag) {
		
		return tag.getTextContent().trim();
	}
	
	public static String createDoubleTag(Element tag) {
		
		String key = tag.getAttribute("key");
		String value = tag.getTextContent();
		
		return key + "=" + value;
	}
	
	public static String createTripleTag(Element tag) {
		
		String namespace = tag.getAttribute("namespace");
		String predicate = tag.getAttribute("predicate");
		String value = tag.getTextContent();
		
		return namespace + ":" + predicate + "=" + value;
	}
	
	public static ImmutableList<Element> getChildElements(Element parent) {
		
		ImmutableList.Builder<Element> childElements = new ImmutableList.Builder<Element>();
		
		NodeList children = parent.getChildNodes();
		for (int i = 0; i < children.getLength(); i++) {
			Node child = children.item(i);
			
			if (child.getNodeType() == Node.ELEMENT_NODE) {
				childElements.add((Element) child);
			}
		}
		
		return childElements.build();
	}
}
